let msg = require('../../util/msg.js');
let save = require('../save.js');
let mem = require('../../util/mem.js');
let log = require('../../util/log.js');
let variable = require('../../data/variable.js');
let rpc = require('../../util/rpc.js');
let gameData = require('../../util/gameData.js');

module.exports = DDZEventHandler;

function DDZEventHandler() {
}

DDZEventHandler.prototype.bidOver = function (table) {
    let param = {};
    param.gameId = table.getTableID();
    param.multiple = table.getMultiple();
    param.playerId = [table.getPlayer(0).getPid(), table.getPlayer(1).getPid(), table.getPlayer(2).getPid()];
    //param.playerId0 = table.getPlayer(0).getPid();
    //param.playerId1 = table.getPlayer(1).getPid();
    //param.playerId2 = table.getPlayer(2).getPid();
    param.playerName = [table.getPlayer(0).getName(), table.getPlayer(1).getName(), table.getPlayer(2).getName()];
    //param.playerName0 = encodeURIComponent(table.getPlayer(0).getName());
    //param.playerName1 = encodeURIComponent(table.getPlayer(1).getName());
    //param.playerName2 = encodeURIComponent(table.getPlayer(2).getName());
    rpc.dc.send('updateGame', param);
};
DDZEventHandler.prototype.gameOver = function (table, result, winnerSeat, ticket, spring, ids) {
    if (!mem.games[table.getTableID()]) {
        return false;
    }
    let game = mem.games[table.getTableID()];
    let gameLv = table.getGameLv();
    let coinType = gameData.d.gameLv[gameLv].coinType;

    if (!this.updateGamePraise(table)) {
        return false;
    }

    let isWinner = this.isWinner(table, winnerSeat);

    let coin = [];
    for (let i = 0; i < 3; i++) {
        let addCoin = (result[i] - ticket);
        if (!table.getPlayer(i).isRobot()) {
            save.saveResult(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, addCoin, coinType, isWinner[i]);
            save.taskUpdate(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, 1, 1);
            save.taskUpdate(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, 5, addCoin);
            if (isWinner[i]) {
                save.taskUpdate(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, 2, 1);
            }
        } else {
            save.robotResult(table.getPlayer(i)._pid, addCoin, coinType, isWinner[i]);
        }
        coin[i] = mem.gamePlayers[table.getPlayer(i)._pid].coin + addCoin;
        delete mem.gamePlayers[table.getPlayer(i)._pid];
    }

    this.sendToPlayer(table, winnerSeat, gameLv, coin, spring, result, ids, isWinner);

    if (game && game.id) {
        delete mem.games[table.getTableID()];
        let param = {};
        param.gameId = table.getTableID();
        rpc.dc.send('delGame', param);
        if (gameData.d.gameLv[gameLv].type == 'custom') {
            rpc.dc.send('delRecruit', param);
        }
    }
    log.p('play end kill room', table.getTableID());
};
DDZEventHandler.prototype.gameOverCustom = function (table, result, winnerSeat, ticket, spring, ids) {
    if (!mem.games[table.getTableID()]) {
        return false;
    }
    let game = mem.games[table.getTableID()];
    let gameLv = table.getGameLv();
    let coinType = gameData.d.gameLv[gameLv].coinType;

    if (!this.updateGamePraise(table)) {
        return false;
    }
    
    let isWinner = this.isWinner(table, winnerSeat);
    
    console.log("DDZEventHandler.prototype.gameOverCustom");
    console.log(game.owerId);
    let coin = [];
    for (let i = 0; i < 3; i++) {
        let addCoin = (result[i] - ticket);
        if (!table.getPlayer(i).isRobot()) {
            console.log(table.getPlayer(i));
            let isOwer = (game.owerId==table.getPlayer(i)._pid);
            if(isOwer){ 
                //扣除房卡
                save.saveCardCost(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid,-1);
            }   
            save.saveAgainResult(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, addCoin, coinType, isWinner[i]);
            save.taskUpdate(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, 1, 1);
            save.taskUpdate(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, 5, addCoin);
            if (isWinner[i]) {
                save.taskUpdate(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, 2, 1);
            }
        } else {
            save.robotResult(table.getPlayer(i)._pid, addCoin, coinType, isWinner[i]);
        }
        mem.gamePlayers[table.getPlayer(i)._pid].ready = false;
        mem.gamePlayers[table.getPlayer(i)._pid].coin += addCoin;
        //if (coinType == 'score' && mem.gamePlayers[table.getPlayer(i)._pid].coin < 0) {
        //    mem.gamePlayers[table.getPlayer(i)._pid].coin = 0;
        //}
        coin[i] = mem.gamePlayers[table.getPlayer(i)._pid][coinType];
    }
    
    this.sendToPlayer(table, winnerSeat, gameLv, coin, spring, result, ids, isWinner);

    let param = {};
    param.gameId = table.getTableID();
    param.id = table.getPlayer(0)._pid;
    param.name = mem.gamePlayers[table.getPlayer(0)._pid].name;
    param.avatar = mem.gamePlayers[table.getPlayer(0)._pid].avatar;
    param.bluedId = mem.gamePlayers[table.getPlayer(0)._pid].bluedId;
    rpc.dc.send('addRecruit', param);
    
    if (game && game.id) {
        mem.games[table.getTableID()].ddz.close();
        mem.games[table.getTableID()].ddz = null;
        table.broadcast('gameNeedReady');
    }

    log.p('play end restart room', table.getTableID());
};
DDZEventHandler.prototype.gameOverArena = function (table, result, winnerSeat, ticket, spring, ids) {
    if (!mem.games[table.getTableID()]) {
        return false;
    }
    let game = mem.games[table.getTableID()];
    let gameLv = table.getGameLv();
    let mode = mem.games[table.getTableID()].mode;

    if (!this.updateGamePraise(table)) {
        return false;
    }

    let isWinner = this.isWinner(table, winnerSeat);

    let coin = [];
    for (let i = 0; i < 3; i++) {
        let addCoin = (result[i] - ticket);
        save.saveArenaResult(table.getPlayer(i)._pid, table.getPlayer(i)._cid, table.getPlayer(i)._uuid, isWinner[i]);
        coin[i] = mem.gamePlayers[table.getPlayer(i)._pid].coin + addCoin;
        delete mem.gamePlayers[table.getPlayer(i)._pid];
    }

    this.sendToPlayer(table, winnerSeat, gameLv, coin, spring, result, ids, isWinner);

    if (game && game.id) {
        delete mem.games[table.getTableID()];
        let param = {};
        param.gameId = table.getTableID();
        rpc.dc.send('delGame', param);
        if (gameData.d.gameLv[gameLv].type == 'custom') {
            rpc.dc.send('delRecruit', param);
        }
    }

    let data = {};
    data.action = 'gameOverArena';
    data.ids = ids;
    data.point = coin;
    data.mode = mode;
    rpc.match.send('rpcInGame', data);

    log.p('play end kill arena room', table.getTableID());
};

DDZEventHandler.prototype.updateGamePraise = function (table) {
    let param = [];
    for (let j = 0; j < 3; j++) {
        if (!mem.gamePlayers[table.getPlayer(j)._pid]) {
            continue;
        }
        param.push({
            'id': table.getPlayer(j)._pid,
            'name': mem.gamePlayers[table.getPlayer(j)._pid].name,
            'isRobot': table.getPlayer(j).isRobot(),
            'task': mem.gamePlayers[table.getPlayer(j)._pid].task
        });
    }
    if (param.length == 0) {
        return false;
    }
    rpc.dc.send('updateGamePraise', param);
    return true;
};
DDZEventHandler.prototype.isWinner = function (table, winnerSeat) {
    let isWinner = [];
    if (winnerSeat == table.getDZ()) {
        isWinner[winnerSeat] = true;
        isWinner[(winnerSeat + 1) % 3] = false;
        isWinner[(winnerSeat + 2) % 3] = false;
    } else {
        isWinner[table.getDZ()] = false;
        isWinner[(table.getDZ() + 1) % 3] = true;
        isWinner[(table.getDZ() + 2) % 3] = true;
    }
    return isWinner;
};
DDZEventHandler.prototype.card = function (table) {
    let card = [];
    card.push(table.getPlayer(0).getHandCards());
    card.push(table.getPlayer(1).getHandCards());
    card.push(table.getPlayer(2).getHandCards());
    return card;
};
DDZEventHandler.prototype.double = function (table) {
    let double = [];
    double.push(table.getPlayer(0).isDouble());
    double.push(table.getPlayer(1).isDouble());
    double.push(table.getPlayer(2).isDouble());
    return double;
};
DDZEventHandler.prototype.sendToPlayer = function (table, winnerSeat, gameLv, coin, spring, result, ids, isWinner) {
    let card = this.card(table);
    let double = this.double(table);
    let multiple = table.getMultiple();
    let multiples = table.getMultiples();
    if (spring != 0) {
        multiple *= 2;
        for (let i in multiples) {
            multiples[i] *= 2;
        }
    }
    table.sendTo(0, 'gameOverStart', {
        'again': false,
        'winner': winnerSeat,
        'multiple': multiple,
        'baseScore': table.getBaseScore(),
        'spring': spring,
        'coinType': gameData.d.gameLv[gameLv].coinType,
        'result': [result[0], result[1], result[2]],
        'ids': [ids[0], ids[1], ids[2]],
        'double': [double[0], double[1], double[2]],
        'multiples': [multiples[0],multiples[1],multiples[2]],
        'coin': coin,
        'card': card,
        'isWinner': isWinner
    });
    table.sendTo(1, 'gameOverStart', {
        'again': false,
        'winner': winnerSeat,
        'multiple': multiple,
        'baseScore': table.getBaseScore(),
        'spring': spring,
        'coinType': gameData.d.gameLv[gameLv].coinType,
        'result': [result[1], result[2], result[0]],
        'ids': [ids[1], ids[2], ids[0]],
        'double': [double[1], double[2], double[0]],
        'multiples': [multiples[1],multiples[2],multiples[0]],
        'coin': coin,
        'card': card,
        'isWinner': isWinner
    });
    table.sendTo(2, 'gameOverStart', {
        'again': false,
        'winner': winnerSeat,
        'multiple': multiple,
        'baseScore': table.getBaseScore(),
        'spring': spring,
        'coinType': gameData.d.gameLv[gameLv].coinType,
        'result': [result[2], result[0], result[1]],
        'ids': [ids[2], ids[0], ids[1]],
        'double': [double[2], double[0], double[1]],
        'multiples': [multiples[2],multiples[0],multiples[1]],
        'coin': coin,
        'card': card,
        'isWinner': isWinner
    });
};